from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from spider.models import (
    CrawlTask,
    RawHTML,
    ListItem,
    DetailItem,
    SubDetailItem,
)


class IdSearchAdmin(admin.ModelAdmin):
    def get_search_results(self, request, queryset, search_term):
        qs, use_distinct = super().get_search_results(request, queryset, search_term)
        term = (search_term or '').strip()
        if term.isdigit():
            try:
                qs = queryset.filter(pk=int(term)) | qs
            except Exception:
                pass
        return qs, use_distinct


@admin.register(CrawlTask)
class CrawlTaskAdmin(IdSearchAdmin):
    list_display = ['id', 'url_short', 'task_type_badge', 'status_badge', 'parent_task_link', 'child_tasks_count', 'retry_count', 'created_at', 'crawled_at']
    list_filter = ['task_type', 'status', 'parent_task', 'created_at', 'updated_at', 'crawled_at']
    search_fields = ['id', 'url', 'error_message']
    readonly_fields = ['created_at', 'updated_at', 'crawled_at', 'error_message_display', 'child_tasks_count_display']
    list_per_page = 50
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
    list_display_links = ['id', 'url_short']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('url', 'task_type', 'status', 'parent_task')
        }),
        ('任务关系', {
            'fields': ('child_tasks_count_display',),
            'classes': ('collapse',)
        }),
        ('重试信息', {
            'fields': ('retry_count',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at', 'crawled_at')
        }),
        ('错误信息', {
            'fields': ('error_message_display',),
            'classes': ('collapse',)
        }),
    )
    
    def url_short(self, obj):
        """显示完整的URL"""
        return format_html('<a href="{}" target="_blank" title="{}">{}</a>', obj.url, obj.url, obj.url)
    url_short.short_description = 'URL'
    
    def task_type_badge(self, obj):
        """任务类型徽章"""
        colors = {
            'list': 'primary',
            'detail': 'success',
            'sub_detail': 'info',
        }
        color = colors.get(obj.task_type, 'secondary')
        return format_html(
            '<span class="badge badge-{}">{}</span>',
            color,
            obj.get_task_type_display()
        )
    task_type_badge.short_description = '任务类型'
    
    def status_badge(self, obj):
        """状态徽章"""
        colors = {
            'pending': 'warning',
            'crawling': 'info',
            'crawled': 'success',
            'failed': 'danger',
        }
        icons = {
            'pending': '⏳',
            'crawling': '🔄',
            'crawled': '✅',
            'failed': '❌',
        }
        color = colors.get(obj.status, 'secondary')
        icon = icons.get(obj.status, '')
        return format_html(
            '<span class="badge badge-{}">{} {}</span>',
            color,
            icon,
            obj.get_status_display()
        )
    status_badge.short_description = '状态'
    
    def error_message_display(self, obj):
        """错误信息显示"""
        if obj.error_message:
            return format_html('<pre style="background: #f5f5f5; padding: 10px; border-radius: 4px;">{}</pre>', obj.error_message)
        return '-'
    error_message_display.short_description = '错误信息'
    
    def parent_task_link(self, obj):
        """显示上级任务链接"""
        if obj.parent_task:
            return format_html(
                '<a href="/admin/spider/crawltask/{}/change/" title="{}">#{}</a> - {}',
                obj.parent_task.id,
                obj.parent_task.url,
                obj.parent_task.id,
                obj.parent_task.url
            )
        return format_html('<span class="text-muted">-</span>')
    parent_task_link.short_description = '上级任务'
    
    def child_tasks_count(self, obj):
        """显示子任务数量"""
        count = obj.child_tasks.count()
        if count > 0:
            return format_html(
                '<a href="/admin/spider/crawltask/?parent_task__id__exact={}">'
                '<span class="badge badge-info">{}</span></a>',
                obj.id,
                count
            )
        return format_html('<span class="badge badge-secondary">0</span>')
    child_tasks_count.short_description = '子任务'
    
    def child_tasks_count_display(self, obj):
        """显示子任务详情"""
        child_tasks = obj.child_tasks.all()
        if child_tasks.exists():
            items_html = ''
            for task in child_tasks[:20]:  # 只显示前20个
                status_color = 'success' if task.status == 'crawled' else 'warning' if task.status == 'pending' else 'danger' if task.status == 'failed' else 'info'
                items_html += format_html(
                    '<li style="margin: 5px 0;">'
                    '<a href="/admin/spider/crawltask/{}/change/">#{}</a> - '
                    '<span class="badge badge-{}">{}</span> - {}'
                    '</li>',
                    task.id,
                    task.id,
                    status_color,
                    task.get_status_display(),
                    task.url
                )
            if child_tasks.count() > 20:
                items_html += format_html('<li style="color: #999;">... 还有 {} 个子任务</li>', child_tasks.count() - 20)
            return format_html('<ul style="list-style: none; padding: 0;">{}</ul>', items_html)
        return format_html('<span class="text-muted">无子任务</span>')
    child_tasks_count_display.short_description = '子任务列表'


@admin.register(RawHTML)
class RawHTMLAdmin(IdSearchAdmin):
    list_display = ['id', 'url_short', 'content_length_badge', 'file_path_short', 'created_at']
    list_filter = ['created_at']
    search_fields = ['id', 'url', 'file_path']
    readonly_fields = ['created_at', 'url', 'html_content_preview', 'content_length', 'file_path', 'task']
    list_per_page = 50
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
    list_display_links = ['id', 'url_short']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('url', 'task')
        }),
        ('内容信息', {
            'fields': ('content_length', 'file_path')
        }),
        ('HTML内容', {
            'fields': ('html_content_preview',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at',)
        }),
    )
    
    def url_short(self, obj):
        """显示完整的URL"""
        return format_html('<a href="{}" target="_blank" title="{}">{}</a>', obj.url, obj.url, obj.url)
    url_short.short_description = 'URL'
    
    def content_length_badge(self, obj):
        """内容长度徽章"""
        length = obj.content_length or 0
        if length > 100000:
            color = 'success'
            size = f'{length // 1024} KB'
        elif length > 10000:
            color = 'info'
            size = f'{length // 1024} KB'
        else:
            color = 'secondary'
            size = f'{length} B'
        return format_html('<span class="badge badge-{}">{}</span>', color, size)
    content_length_badge.short_description = '内容长度'
    
    def file_path_short(self, obj):
        """显示缩短的文件路径"""
        if obj.file_path:
            path = obj.file_path[:50] + '...' if len(obj.file_path) > 50 else obj.file_path
            return format_html('<code>{}</code>', path)
        return format_html('<span class="text-muted">-</span>')
    file_path_short.short_description = '文件路径'
    
    def html_content_preview(self, obj):
        """HTML内容预览"""
        if obj.html_content:
            preview = obj.html_content[:500] + '...' if len(obj.html_content) > 500 else obj.html_content
            return format_html('<pre style="max-height: 300px; overflow: auto;">{}</pre>', preview)
        return '-'
    html_content_preview.short_description = 'HTML内容预览'


@admin.register(ListItem)
class ListItemAdmin(IdSearchAdmin):
    list_display = ['id', 'title_short', 'province_badge', 'business_type_badge', 'info_type', 'publish_time', 'created_at']
    list_filter = ['province', 'business_type', 'info_type', 'industry', 'source_platform', 'publish_time', 'created_at']
    search_fields = ['id', 'title', 'url', 'province', 'business_type', 'info_type', 'industry', 'source_platform']
    readonly_fields = ['created_at', 'updated_at', 'url_link']
    list_per_page = 50
    date_hierarchy = 'publish_time'
    ordering = ['-publish_time', '-created_at']
    list_display_links = ['id', 'title_short']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'url_link')
        }),
        ('分类信息', {
            'fields': ('province', 'business_type', 'info_type', 'industry', 'source_platform')
        }),
        ('时间信息', {
            'fields': ('publish_time', 'created_at', 'updated_at')
        }),
    )
    
    def title_short(self, obj):
        """显示完整标题"""
        return format_html('<strong>{}</strong>', obj.title)
    title_short.short_description = '标题'
    
    def province_badge(self, obj):
        """省份徽章"""
        if obj.province:
            return format_html('<span class="badge badge-info">{}</span>', obj.province)
        return '-'
    province_badge.short_description = '省份'
    
    def business_type_badge(self, obj):
        """业务类型徽章"""
        if obj.business_type:
            return format_html('<span class="badge badge-primary">{}</span>', obj.business_type)
        return '-'
    business_type_badge.short_description = '业务类型'
    
    def url_link(self, obj):
        """URL链接"""
        if obj.url:
            return format_html('<a href="{}" target="_blank">{}</a>', obj.url, obj.url)
        return '-'
    url_link.short_description = 'URL'


@admin.register(DetailItem)
class DetailItemAdmin(IdSearchAdmin):
    list_display = ['id', 'project_number', 'info_source_badge', 'list_item_link', 'sub_detail_count', 'created_at']
    list_filter = ['created_at', 'updated_at', 'info_source']
    search_fields = ['id', 'project_number', 'info_source', 'list_item__title', 'list_item__url']
    readonly_fields = ['created_at', 'updated_at', 'project_number', 'info_source', 'list_item', 'task', 'sub_detail_urls_display']
    list_per_page = 50
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
    list_display_links = ['id', 'project_number']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('project_number', 'info_source', 'list_item', 'task')
        }),
        ('子详情页', {
            'fields': ('sub_detail_urls_display',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at')
        }),
    )
    
    def info_source_badge(self, obj):
        """信息来源徽章"""
        if obj.info_source:
            return format_html('<span class="badge badge-success">{}</span>', obj.info_source)
        return '-'
    info_source_badge.short_description = '信息来源'
    
    def list_item_link(self, obj):
        """关联列表项链接"""
        if obj.list_item:
            return format_html(
                '<a href="/admin/spider/listitem/{}/change/">{}</a>',
                obj.list_item.id,
                obj.list_item.title
            )
        return '-'
    list_item_link.short_description = '列表项'
    
    def sub_detail_count(self, obj):
        """显示子详情页数量"""
        count = obj.sub_detail_items.count()
        if count > 0:
            return format_html(
                '<a href="/admin/spider/subdetailitem/?detail_item__id__exact={}">'
                '<span class="badge badge-success">{}</span></a>',
                obj.id,
                count
            )
        return format_html('<span class="badge badge-secondary">0</span>')
    sub_detail_count.short_description = '子详情页'
    
    def sub_detail_urls_display(self, obj):
        """子详情页URL列表"""
        urls = obj.sub_detail_urls or []
        if urls:
            html = '<ul style="list-style: none; padding: 0;">'
            for url in urls[:10]:  # 只显示前10个
                html += f'<li style="margin: 5px 0;"><a href="{url}" target="_blank">{url}</a></li>'
            if len(urls) > 10:
                html += f'<li style="color: #999;">... 还有 {len(urls) - 10} 个</li>'
            html += '</ul>'
            return format_html(html)
        return '-'
    sub_detail_urls_display.short_description = '子详情页URL列表'


@admin.register(SubDetailItem)
class SubDetailItemAdmin(IdSearchAdmin):
    list_display = ['id', 'url_short', 'detail_item_link', 'html_length_badge', 'created_at']
    list_filter = ['created_at', 'detail_item__info_source']
    search_fields = ['id', 'url', 'detail_item__project_number', 'detail_item__list_item__title']
    readonly_fields = ['created_at', 'url', 'html_content_preview', 'detail_item', 'task']
    list_per_page = 50
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
    list_display_links = ['id', 'url_short']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('url', 'detail_item', 'task')
        }),
        ('HTML内容', {
            'fields': ('html_content_preview',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at',)
        }),
    )
    
    def url_short(self, obj):
        """显示完整的URL"""
        return format_html('<a href="{}" target="_blank" title="{}">{}</a>', obj.url, obj.url, obj.url)
    url_short.short_description = 'URL'
    
    def detail_item_link(self, obj):
        """显示关联的详情项链接"""
        if obj.detail_item:
            return format_html(
                '<a href="/admin/spider/detailitem/{}/change/" class="badge badge-info">{}</a>',
                obj.detail_item.id,
                obj.detail_item.project_number
            )
        return '-'
    detail_item_link.short_description = '关联详情项'
    
    def html_length_badge(self, obj):
        """显示HTML内容长度徽章"""
        length = len(obj.html_content) if obj.html_content else 0
        if length > 10000:
            color = 'success'
            size = f'{length // 1024} KB'
        elif length > 1000:
            color = 'warning'
            size = f'{length // 1024} KB'
        else:
            color = 'secondary'
            size = f'{length} B'
        return format_html('<span class="badge badge-{}">{}</span>', color, size)
    html_length_badge.short_description = '内容长度'
    
    def html_content_preview(self, obj):
        """HTML内容预览"""
        if obj.html_content:
            preview = obj.html_content[:1000] + '...' if len(obj.html_content) > 1000 else obj.html_content
            return format_html('<pre style="max-height: 400px; overflow: auto; background: #f5f5f5; padding: 10px; border-radius: 4px;">{}</pre>', preview)
        return '-'
    html_content_preview.short_description = 'HTML内容预览'
